﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Windows.Forms;


namespace 多行记录合并
{
    class MergeText
    {
        
        public static bool IsSelectionValid(bool bWithHead)
        {
            Excel.Range rngInput = Globals.ThisAddIn.Application.Selection;
            if (rngInput.Cells.Columns.Count != 2 || rngInput.Rows.Count < 3)
            {
                return false;
            }
            return true;
        }

        public static void DoMergeText(bool bWithHead)
        {
            Excel.Range rngInput = Globals.ThisAddIn.Application.Selection;
            if (!IsSelectionValid(bWithHead))
            {
                MessageBox.Show("请选择3行以上，2列区域。");
                return;
            }

            Dictionary<string, List<string>> dataDict = new Dictionary<string, List<string>>();

            int iRow = 1;
            if (bWithHead)
            {
                iRow = 2;
            }
            for (; iRow <= rngInput.Rows.Count; ++iRow)
            {
                string key = rngInput.Cells[iRow, 1].Value2;
                string val = rngInput.Cells[iRow, 2].Value2;

                key = key.Trim();
                val = val.Trim();

                List<string> listVal = null;
                if (!dataDict.ContainsKey(key))
                {
                    listVal = new List<string>();
                    dataDict[key] = listVal;
                }
                else
                {
                    listVal = dataDict[key];
                }
                listVal.Add(val);
            }



            Excel.Range rngResult;
            try
            {
                rngResult = Globals.ThisAddIn.Application.InputBox("选择目标首地址", Type: 8);
                rngResult = rngResult.Resize[dataDict.Keys.Count + 1, 2];
            }
            catch (Exception err)
            {
                return;
            }

            int iRstRow = 1;
            if (bWithHead)
            {
                rngResult.Cells[1, 1] = rngInput.Cells[1, 1];
                rngResult.Cells[1, 2] = rngInput.Cells[1, 2];
                iRstRow = 2;
            }
            foreach (var k in dataDict.Keys)
            {
                var listVal = dataDict[k];
                rngResult.Cells[iRstRow, 1] = k;
                rngResult.Cells[iRstRow, 2] = string.Join("/", listVal.ToArray());
                iRstRow++;
            }
        }
    }
}
